/*
 * @Copyright: 2023 - 2023 www.hoperun.com Inc. All rights reserved.
 */

package com.lifeservice.framework.security.filter;

import com.alibaba.fastjson2.JSON;
import com.lifeservice.common.config.LifeServiceConfig;
import com.lifeservice.common.constant.HttpStatus;
import com.lifeservice.common.core.domain.AjaxResult;
import com.lifeservice.common.core.redis.RedisCache;
import com.lifeservice.common.utils.HmacSHA256Util;
import com.lifeservice.common.utils.ServletUtils;
import com.lifeservice.common.utils.StringUtils;
import com.lifeservice.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author liu_yifeng
 * @function wx接口鉴权，放开login与homepage接口
 * @date 2023/3/2 16:47
 */
@Component
public class WxAuthTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private LifeServiceConfig lifeServiceConfig;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        int code = HttpStatus.UNAUTHORIZED;
        String msg = "";
        String url = request.getRequestURI();
        if (url.startsWith("/wx") && !url.startsWith("/wx/homepage") && !url.startsWith("/wx/wxlogin")) {
            String token = request.getHeader("token");
            if (StringUtils.isEmpty(token)) {
                msg = StringUtils.format("认证失败，无法访问资源", request.getRequestURI());
            } else {
                token = HmacSHA256Util.hmacSHA256(lifeServiceConfig.getHmacKey(), token);
                Object wxUser = redisCache.getCacheObject(token);
                if (null == wxUser) {
                    msg = StringUtils.format("认证失败，无法访问资源", request.getRequestURI());
                }
            }
        }
        if (StringUtils.isNotEmpty(msg)) {
            ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
        } else {
            chain.doFilter(request, response);
        }
    }
}
